import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { ScanStats } from '../types/ssh'

export const useStatsStore = defineStore('stats', () => {
  const stats = ref<ScanStats | null>(null)
  const loading = ref(false)
  const error = ref<string | null>(null)

  const fetchStats = async () => {
    loading.value = true
    error.value = null
    
    try {
      const response = await fetch('/api/v2/stats')
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      const data = await response.json()
      console.log('Fetched stats data:', data)
      stats.value = data.stats
      console.log('Updated stats:', stats.value)
    } catch (err) {
      error.value = err instanceof Error ? err.message : 'Failed to fetch stats'
      console.error('Error fetching stats:', err)
    } finally {
      loading.value = false
    }
  }

  // 清理统计数据
  const clearStats = () => {
    stats.value = null
    console.log('Stats cleared.')
  }

  return { stats, loading, error, fetchStats, clearStats }
})